package com.whereta.service.impl;

import com.github.pagehelper.PageInfo;
import com.whereta.dao.*;
import com.whereta.model.*;
import com.whereta.service.IAccountService;
import com.whereta.vo.ResultVO;
import com.whereta.vo.UserCreateVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author Vincent
 * @time 2015/8/27 17:10
 */
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
    @Resource
    private IAccountDao accountDao;
    @Resource
    private IAccountRoleDao accountRoleDao;
    @Resource
    private IRoleDao roleDao;
    @Resource
    private IRolePermissionDao rolePermissionDao;
    @Resource
    private IPermissionDao permissionDao;
    @Resource
    private IQueryAccountPermissionDao queryAccountPermissionDao;
    @Resource
    private IDepartmentAccountDao departmentAccountDao;
    @Resource
    private IDepartmentDao departmentDao;

    /**
     * 根据账号获取账号对象
     *
     * @param account
     * @return
     */
    public Account getAccountByAccount(String account) {
        return accountDao.getByAccount(account);
    }

    /**
     * 账号管理
     *
     * @return
     */
    public ResultVO selectAccount(int userId, int pageNow, int pageSize) {
        ResultVO resultVO = new ResultVO(true);
        Map<String, Object> map = new HashMap<String, Object>();
        //获取用户部门id
        Integer depIdByAccountId = departmentAccountDao.getDepIdByAccountId(userId);
        if (depIdByAccountId == null) {
            resultVO.setOk(false);
            resultVO.setMsg("用户部门不存在");
            return resultVO;
        }
        //获取所有部门
        List<Department> departments = departmentDao.selectAll();
        //获取所有子级部门id集合
        Set<Integer> childrenDepIds = DepartmentServiceImpl.getChildrenDepIds(departments, depIdByAccountId);
        childrenDepIds.add(depIdByAccountId);
        //排除不查询的账号id
        Set<Integer> excludeAccountIdSet = new HashSet<>();
        excludeAccountIdSet.add(userId);


        PageInfo<Map> pageInfo = accountDao.selectAccountManage(childrenDepIds, excludeAccountIdSet, pageNow, pageSize);
        List<Map> mapList = pageInfo.getList();

        //获取所有角色
        List<Role> roles = roleDao.selectAll();
        for (Map m : mapList) {
            Object idObj = m.get("id");
            //用户角色id集合
            Set<Integer> roleIdSet = accountRoleDao.selectRoleIdSet(Integer.parseInt(idObj.toString()));
            String roleNames = "";
            for (Integer roleId : roleIdSet) {
                Role role = roleDao.get(roles, roleId);
                roleNames += "," + role.getName();
            }
            if (StringUtils.isNotBlank(roleNames)) {
                roleNames = roleNames.substring(1);
            }
            m.put("roleNames", roleNames);
        }
        map.put("total", pageInfo.getTotal());
        map.put("rows", mapList);
        resultVO.setData(map);
        return resultVO;
    }

    /**
     * 根据账号id获取授权
     *
     * @param accountId
     * @return
     */
    public SimpleAuthorizationInfo getAccountRolePermission(int accountId) {
        SimpleAuthorizationInfo token = new SimpleAuthorizationInfo();
        //获取所有权限
        List<Permission> permissionList = permissionDao.selectAll();
        //用户角色名字
        Set<String> roleNameSet = new HashSet<String>();
        //权限名字
        Set<String> perNameSet = new HashSet<String>();
        //获取所有角色
        List<Role> roles = roleDao.selectAll();
        //获取用户角色id
        Set<Integer> roleIdSet = accountRoleDao.selectRoleIdSet(accountId);
        if (roleIdSet != null && !roleIdSet.isEmpty()) {
            for (Integer roleId : roleIdSet) {
                Role role = roleDao.get(roles, roleId);
                if (role != null) {
                    roleNameSet.add(role.getKey());
                }
                //获取权限id集合
                Set<Integer> permissionIdSet = rolePermissionDao.getPermissionIdSetByRoleId(roleId);
                if (permissionIdSet != null && !permissionIdSet.isEmpty()) {
                    for (Integer permissionId : permissionIdSet) {
                        //获取权限
                        Permission permission = permissionDao.get(permissionList, permissionId);
                        String key = permission.getKey();
                        if (StringUtils.isNotBlank(key)) {
                            perNameSet.add(key);
                        }
                    }
                }
            }
        }
        //设置角色权限
        token.setRoles(roleNameSet);
        token.setStringPermissions(perNameSet);
        return token;
    }

    /**
     * 添加账号
     *
     * @param createVO
     * @return
     */
    @Override
    public ResultVO saveUser(UserCreateVO createVO) {
        ResultVO resultVO = new ResultVO(true);
        Account byAccount = accountDao.getByAccount(createVO.getAccount());
        if (byAccount != null) {
            resultVO.setOk(false);
            resultVO.setMsg("账号已存在");
            return resultVO;
        }
        //保存
        Account account = new Account();
        account.setAccount(createVO.getAccount());
        account.setPassword(createVO.getPassword());
        account.setRegisterTime(new Date());
        accountDao.save(account);

        DepartmentAccount departmentAccount = new DepartmentAccount();
        departmentAccount.setAccountId(account.getId());
        departmentAccount.setDepId(createVO.getDep());
        departmentAccountDao.save(departmentAccount);
        resultVO.setMsg("注册成功");
        return resultVO;
    }

    /**
     * 删除用户
     *
     * @param userId
     * @return
     */
    @Override
    public ResultVO deleteUser(int userId) {
        ResultVO resultVO = new ResultVO(true);
        //删除账号
        accountDao.delete(userId);
        //删除账号与角色关联
        accountRoleDao.deleteByAccountId(userId);
        //删除账号与部门关联
        departmentAccountDao.deleteByAccountId(userId);
        resultVO.setMsg("删除账号成功");
        return resultVO;
    }

    /**
     * 修改用户部门
     *
     * @param userId
     * @param depId
     * @return
     */
    @Override
    public ResultVO updateUserDep(int userId, int depId) {
        ResultVO resultVO = new ResultVO(true);

        Integer depIdByAccountId = departmentAccountDao.getDepIdByAccountId(userId);
        if (depIdByAccountId != null) {
            departmentAccountDao.deleteByAccountId(userId);
        }
        DepartmentAccount departmentAccount = new DepartmentAccount();
        departmentAccount.setDepId(depId);
        departmentAccount.setAccountId(userId);
        departmentAccountDao.save(departmentAccount);
        resultVO.setMsg("修改用户部门成功");
        return resultVO;
    }

    /**
     * 分配用户角色
     *
     * @param userId
     * @param roleIds
     * @return
     */
    @Override
    public ResultVO updateUserRole(int userId, String roleIds) {
        ResultVO resultVO = new ResultVO(true);
        //删除角色
        accountRoleDao.deleteByAccountId(userId);

        String[] roleIdArray = roleIds.split(",");
        if (StringUtils.isNotBlank(roleIds)&&roleIdArray != null && roleIdArray.length > 0) {
            for(String roleId:roleIdArray){
                AccountRole accountRole = new AccountRole();
                accountRole.setRoleId(Integer.parseInt(roleId));
                accountRole.setAccountId(userId);
                accountRoleDao.createAccountRole(accountRole);
            }
        }

        resultVO.setMsg("分配用户角色成功");
        return resultVO;
    }
}
